package org.jeecg.modules.manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.constant.RedisCacheConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiTaskSettle;
import org.jeecg.modules.manage.entity.CaishuiTaskSettleItem;
import org.jeecg.modules.manage.service.IMCaishuiCompanySetService;
import org.jeecg.modules.manage.service.IMCaishuiTaskSettleItemService;
import org.jeecg.modules.manage.service.IMCaishuiTaskSettleService;
import org.jeecg.modules.manage.vo.CaishuiTaskSettlePage;
import org.jeecg.modules.manage.vo.ServiceFeeVo;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 任务结算[管理]
 * @Author: yfkj
 * @Date: 2023-02-20
 * @Version: V1.0
 */
@Api(tags = "任务结算[管理]")
@RestController
@RequestMapping("/manageApi/caishuiTaskSettle")
@Slf4j
public class MCaishuiTaskSettleController {

    @Autowired
    private IMCaishuiTaskSettleService imCaishuiTaskSettleService;
    @Autowired
    private IMCaishuiTaskSettleItemService imCaishuiTaskSettleItemService;
    @Resource
    private IMCaishuiCompanySetService imCaishuiCompanySetService;
    @Autowired
    private RabbitMqClient rabbitMqClient;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param caishuiTaskSettle
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "任务结算[管理]-分页列表查询", notes = "任务结算[管理]-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CaishuiTaskSettle>> queryPageList(CaishuiTaskSettle caishuiTaskSettle,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<CaishuiTaskSettle> queryWrapper = QueryGenerator.initQueryWrapper(caishuiTaskSettle, req.getParameterMap());
        Page<CaishuiTaskSettle> page = new Page<CaishuiTaskSettle>(pageNo, pageSize);
        IPage<CaishuiTaskSettle> pageList = imCaishuiTaskSettleService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询任务结算[管理]详情
     *
     * @param caishuiTaskSettleItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "任务结算[管理]-分页列表查询任务结算详情", notes = "任务结算[管理]-分页列表查询任务结算详情")
    @GetMapping(value = "/itemList")
    public Result<IPage<CaishuiTaskSettleItem>> queryPageitemList(CaishuiTaskSettleItem caishuiTaskSettleItem,
                                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest req) {
        QueryWrapper<CaishuiTaskSettleItem> queryWrapper = QueryGenerator.initQueryWrapper(caishuiTaskSettleItem, req.getParameterMap());
        Page<CaishuiTaskSettleItem> page = new Page<CaishuiTaskSettleItem>(pageNo, pageSize);
        IPage<CaishuiTaskSettleItem> pageList = imCaishuiTaskSettleItemService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 下发（招行银企直连）
     * @param caishuiTaskSettle
     * @return
     */
    @AutoLog(value = "任务结算[管理]-下发（招行银企直连）")
    @PostMapping(value = "/doIssuedSalary")
    public Result<?> doIssuedSalary(@RequestBody CaishuiTaskSettle caishuiTaskSettle) {
        try {
            //根据账号查询服务公司设置相关信息
            BankSetDTO bankSetDTO = imCaishuiCompanySetService.queryCompanySet(caishuiTaskSettle.getPayAccount());
            //判断发放金额是否足够
            double bankBalance = 0.00;
            Result result = CMBApi.querySubUnitBalance(caishuiTaskSettle.getPayAccount(),caishuiTaskSettle.getPaySubUnit(), bankSetDTO);
            if(result.isSuccess()){
                bankBalance = oConvertUtils.getDouble(result.getResult().toString(),0.00);
            }
            if(bankBalance <= 0){
                return Result.error("账户余额不足！");
            }
            //需支付总额 = 代发总金额 + 服务费
            double amount = caishuiTaskSettle.getTotalAmount().add(BigDecimal.valueOf(caishuiTaskSettle.getServiceFee()))
                    .setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            if(bankBalance < amount){
                return Result.error("账户余额不足！");
            }

            /**1、同步处理*/
            return imCaishuiTaskSettleService.doSubmit(caishuiTaskSettle, bankSetDTO);

//            /**2、异步处理*/
//            BaseMap map = new BaseMap();
//            map.put("caishuiTaskSettle", caishuiTaskSettle);//任务结算数据
//            map.put("bankSetDTO", bankSetDTO);//服务公司设置
//            //防止重复提交
//            redisUtil.incr(RedisCacheConstant.YSW_ISSUED_REPEAT_CACHE + ":" + caishuiTaskSettle.getId(),1);
//            rabbitMqClient.sendMessage("caisui_issued_queue", map);
//            return Result.OK("下发成功，请耐心等待银行处理！");
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error("下发失败！" + e.getMessage());
        }
    }

    /**
     * 处理下发批次与明细查询
     * @param orderNo
     * @return
     */
    @ApiOperation(value = "任务结算[管理]-处理下发批次与明细查询", notes = "任务结算[管理]-处理下发批次与明细查询")
    @GetMapping(value = "/handleTaskSettle")
    public Result<?> handleTaskSettle(@RequestParam(name = "orderNo", required = true) String orderNo) {
        imCaishuiTaskSettleService.handleTaskSettle(orderNo);
        return Result.OK();
    }

    /**
     * 计算下发服务费
     * @param idCard
     * @param amount
     * @param taxRate
     * @param taxRateTwo
     * @return
     */
    @ApiOperation(value = "任务结算[管理]-计算下发服务费", notes = "任务结算[管理]-计算下发服务费")
    @GetMapping(value = "/handleServiceFee")
    public Result<ServiceFeeVo> handleServiceFee(@RequestParam(name = "idCard", required = true) String idCard,
                                                 @RequestParam(name = "amount", required = true) Double amount,
                                                 @RequestParam(name = "taxRate", required = true) Double taxRate,
                                                 @RequestParam(name = "taxRateTwo", required = true) Double taxRateTwo) {
        return imCaishuiTaskSettleService.handleServiceFee(idCard, amount, taxRate, taxRateTwo);
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "任务结算[管理]-通过主表ID查询", notes = "任务结算[管理]-通过主表ID查询")
    @GetMapping(value = "/queryCaishuiTaskSettleItemByMainId")
    public Result<IPage<CaishuiTaskSettleItem>> queryCaishuiTaskSettleItemListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<CaishuiTaskSettleItem> caishuiTaskSettleItemList = imCaishuiTaskSettleItemService.selectByMainId(id);
        IPage<CaishuiTaskSettleItem> page = new Page<>();
        page.setRecords(caishuiTaskSettleItemList);
        page.setTotal(caishuiTaskSettleItemList.size());
        return Result.OK(page);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param caishuiTaskSettle
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CaishuiTaskSettle caishuiTaskSettle) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<CaishuiTaskSettle> queryWrapper = QueryGenerator.initQueryWrapper(caishuiTaskSettle, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<CaishuiTaskSettle> caishuiTaskSettleList = imCaishuiTaskSettleService.list(queryWrapper);

        // Step.3 组装pageList
        List<CaishuiTaskSettlePage> pageList = new ArrayList<CaishuiTaskSettlePage>();
        for (CaishuiTaskSettle main : caishuiTaskSettleList) {
            CaishuiTaskSettlePage vo = new CaishuiTaskSettlePage();
            BeanUtils.copyProperties(main, vo);
            List<CaishuiTaskSettleItem> caishuiTaskSettleItemList = imCaishuiTaskSettleItemService.selectByMainId(main.getId());
            vo.setCaishuiTaskSettleItemList(caishuiTaskSettleItemList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "任务结算[管理]列表");
        mv.addObject(NormalExcelConstants.CLASS, CaishuiTaskSettlePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("任务结算[管理]数据", "导出人：" + sysUser.getRealname(), "任务结算[管理]"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

}
